﻿/************************************************************************

   Extended Silverlight Toolkit

   Copyright (C) 2010-2012 Xceed Software Inc.

   This program is provided to you under the terms of the Microsoft Public
   License (Ms-PL) as published at http://extendedsilverlight.codeplex.com/license

   Please purchase a commercial version of this toolkit if you are using
   it in a commercial product. The commercial versions support the project,
   and also include more features for each control, priority support,
   source code, updates, removed watermark, and a proprietary license.

   Visit http://xceed.com and follow @datagrid on Twitter.

  **********************************************************************/

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Data;
using System.Diagnostics;
using System.Globalization;
using System.Collections;

namespace Xceed.Silverlight.ListBox
{
  internal class BindingPathValueExtractor : FrameworkElement
  {
    #region CONSTRUCTORS

    public BindingPathValueExtractor( PropertyPath propertyPath )
    {
      m_binding = new Binding();

      m_binding.Path = propertyPath;
      m_binding.Mode = BindingMode.OneWay;

      this.SetBinding( BindingPathValueExtractor.ValueProperty, m_binding );
    }

    #endregion CONSTRUCTORS

    #region ValueProperty

    private static object UninitializedValueKey = new object();

    private static readonly DependencyProperty ValueProperty = DependencyProperty.Register(
      "Value", typeof( object ), typeof( BindingPathValueExtractor ), new PropertyMetadata( BindingPathValueExtractor.UninitializedValueKey ) );

    private object Value
    {
      get
      {
        object value = this.GetValue( BindingPathValueExtractor.ValueProperty );

        if( value == BindingPathValueExtractor.UninitializedValueKey )
          value = null;

        if( value == DependencyProperty.UnsetValue ) 
          return null;

        return value;
      }
    }

    #endregion ValueProperty

    #region PUBLIC METHODS

    public object GetValueFromItem( object item )
    {
      try
      {
        this.DataContext = item;

        return this.Value;
      }
      finally
      {
        // Might want to not set to null so that the binding is not re-invalidated.
        this.DataContext = null;
      }
    }

    #endregion PUBLIC METHODS

    #region PRIVATE FIELDS

    private Binding m_binding;

    #endregion PRIVATE FIELDS
  }
}
